package cn.dogeye.handlers;

import cn.dogeye.common.protocol.Result;
import cn.dogeye.util.JwtUtil;
import cn.dogeye.util.RespUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.impl.DefaultClaims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.stream.Collectors;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String auths = authentication.getAuthorities().stream().map(a -> a.getAuthority()).collect(Collectors.joining(","));
        Claims claims = new DefaultClaims().setSubject(authentication.getName());
        claims.put("authority",auths);
        String jwt = jwtUtil.createToken(claims);
        response.setHeader(jwtUtil.getHeader(),jwt);
        RespUtil.write(response,Result.succ("登录成功"));
    }
}
